import type { PageType } from '../../../../../lib/page_handler/type'
import type {
  BaseStyleConfig,
  IPersonalizationItemConfig,
  PlatformTypeValue,
} from '../../../../../types/interfaces'
import { RangeSlider } from '../../../../../components/range_slider'
import { UserPref } from '../../../../../lib/abstract'
import { ElementManager } from '../../../../../lib/element_manager'
import { BaiduPageType } from '../../../../../lib/page_handler/platform/baidu/types'
import { GreasyForkPageType } from '../../../../../lib/page_handler/platform/greasyfork/types'
import { ConfigManager } from '../../../../../module/config_manager'
import { AppModule } from '../../../../../module/config_manager/types'
import { UserAnalytics } from '../../../../../module/page_enhancer/data_presentation/platform/greasy_fork/user_analytics'
import { USER_ANALYTICS_MAX_COMMENT_PAGES } from '../../../../../module/page_enhancer/data_presentation/platform/greasy_fork/user_analytics/types'
import { AutoPagination } from '../../../../../module/page_enhancer/interaction/auto_pagination'
import {
  HOSTNAME,
  logger,
  SUPPORTED_PLATFORMS,
  VALID_RESULT,
} from '../../../../../types/constants'

enum PageNumType {
  AutoPagination = 'autoPagination',
  UserAnalytics = 'userAnalytics',
}

interface PageNumConfig {
  remark: string
  defaultPageNum: number
  maxPageNum: number
  apply: () => void
}

const PAGE_NUM_CONFIG: (instance: PageNum) => Record<PageNumType, PageNumConfig> = instance => ({
  [PageNumType.AutoPagination]: {
    remark: '【自动分页】用于设置批量加载时需要处理的页数, 0 表示加载所有页',
    defaultPageNum: 0,
    maxPageNum: ElementManager.getInstance().maxPageNum,
    apply: () => {
      AutoPagination.getInstance().updateLoadAllButton()
      logger.info(`[${instance.name}] 更新分页分隔符-加载所有的样式`)
    },
  },
  [PageNumType.UserAnalytics]: {
    remark: '【用户分析】用于设置留言加载页数, 0 表示加载所有页',
    defaultPageNum: USER_ANALYTICS_MAX_COMMENT_PAGES,
    maxPageNum: USER_ANALYTICS_MAX_COMMENT_PAGES,
    apply: () => {
      if (!instance.userAnalytics)
        instance.userAnalytics = UserAnalytics.getInstance()

      if (instance.userAnalytics.isDashboardRendered) {
        instance.userAnalytics.reset()
        logger.info(`[${instance.name}] 已重置用户分析`)
      }
    },
  },
})

export class PageNum extends UserPref {
  // @Decorators.Identity
  readonly id = 'page_num'
  readonly name = 'PageNum'
  // @Decorators.Dependency
  userAnalytics: UserAnalytics | null = null
  // @Decorators.InheritedCoreConfig
  usePageTypeIsolation = true
  readonly supportedPages: Partial<Record<PlatformTypeValue, PageType[]>> | '*' = {
    [SUPPORTED_PLATFORMS.BAI_DU]: [
      BaiduPageType.Web,
      BaiduPageType.News,
    ],
    [SUPPORTED_PLATFORMS.GREASY_FORK]: [
      GreasyForkPageType.SCRIPT_LIST,
      GreasyForkPageType.SCRIPT_VERSIONS,
      GreasyForkPageType.SCRIPT_FEEDBACK,
      GreasyForkPageType.USER_PROFILE,
    ],
  }

  // @Decorators.InheritedConfig
  readonly styleConfigKey = 'pageNum'
  readonly cssProperty = ''
  readonly cssValueSuffix = ''
  // @Decorators.UIElement
  private readonly rangeSliderLabel: string = '加载页数'
  private readonly defaultMinPageNum: number = 0
  // @Decorators.Config
  private readonly pageNumConfig: PageNumConfig = this.isGreasyForkUserProfile()
    ? PAGE_NUM_CONFIG(this)[PageNumType.UserAnalytics]
    : PAGE_NUM_CONFIG(this)[PageNumType.AutoPagination]

  constructor(config: IPersonalizationItemConfig) {
    super(config)
  }

  createComponent(config: BaseStyleConfig, value: string, _mode: string, debouncedSave: (() => void) & { flush: () => void }): RangeSlider {
    const id = this.generateId(config.styleVar)
    const { remark, defaultPageNum, maxPageNum } = this.pageNumConfig

    return new RangeSlider({
      id,
      label: this.rangeSliderLabel,
      value: Math.min(Number(value) || defaultPageNum, maxPageNum),
      min: this.defaultMinPageNum,
      max: maxPageNum,
      step: 1,
      title: remark,
      onChange: (value) => {
        this.cachedValues.set(id, String(value))
        debouncedSave()
      },
      showValue: true,
      disabled: !ConfigManager.getInstance().getFeatureEnabled(AppModule.AutoPagination.id),
    })
  }

  /**
   * 是否为 Greasy Fork 用户页面
   */
  isGreasyForkUserProfile(): boolean {
    return HOSTNAME === SUPPORTED_PLATFORMS.GREASY_FORK && this.pageType === GreasyForkPageType.USER_PROFILE
  }

  // 由于直接使用的是 input[type="range"] 传递的值，所以不需要额外的校验逻辑
  handleCheck(_value: string): { status: ValidResultType, error: string } {
    return { status: VALID_RESULT.VALID.value, error: '' }
  }

  applyStyles(): void {
    this.getInstanceIds().forEach((_id) => {
      this.pageNumConfig.apply()
    })
  }
}
